package com.itheima.health.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.MenuDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.pojo.Menu;
import com.itheima.health.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;


    @Override
    public List<Menu> findMenu(Integer roleId) {

        List<Menu> allMenu = menuDao.findMenu(roleId);

        List<Menu> list = new ArrayList<>();

        for (Menu menu : allMenu) {
            if(menu.getParentMenuId()==null) {
                list.add(menu);
                List<Menu> childMenu = menuDao.findChildMenu(menu.getId());
                menu.setChildren(childMenu);
            }
        }

        return list;

    }

    @Override
    public PageResult pageQuery(Integer currentPage, String queryString, Integer pageSize) {

        if (currentPage!=null && pageSize!=null) {
            //使用分页插件PageHelper, 设置当前页, 每页最多显示的记录数
            PageHelper.startPage(currentPage, pageSize);
        }

        //响应分页插件的page对象
        Page<Menu> page = menuDao.selectByCondition(queryString);

        return new PageResult(page.getTotal(), page.getResult());

    }

    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    @Override
    public void update(Menu menu) {
        menuDao.update(menu);
    }

    @Override
    public Menu findById(Integer id) {

        Menu menu = menuDao.findById(id);

        return menu;

    }

    @Override
    public List<Menu> selectAll(Integer id) {

        List<Menu> list = menuDao.selectAll();

        return list;

    }

    @Override
    public void delete(Integer id) {
        try {
            menuDao.deleteById(id);
        } catch (Exception e) {
            throw new RuntimeException("删除的检查项在检查组中存在引用关系，不能删除，请先删除中间表的数据");
        }
    }
}
